"""
简化的校园数字孪生系统 - 主应用入口
Simplified Campus Digital Twin System - Main Application Entry
"""
import sys
import logging
from pathlib import Path
from contextlib import asynccontextmanager

from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware

# 添加项目根目录到Python路径
sys.path.insert(0, str(Path(__file__).parent))

from config.settings import settings
from config.logging_config import setup_logging


@asynccontextmanager
async def lifespan(app: FastAPI):
    """应用生命周期管理"""
    # 启动时执行
    logging.info("简化校园数字孪生系统启动中...")
    
    # 初始化数据库
    try:
        from database.simple_db import initialize_database
        initialize_database()
        logging.info("数据库初始化完成")
    except Exception as e:
        logging.warning(f"数据库初始化失败: {e}")
    
    # 同步WVP数据
    try:
        from services.wvp_service_unified import get_unified_wvp_service
        wvp_service = get_unified_wvp_service()
        sync_result = await wvp_service.sync_wvp_devices_and_channels()
        if sync_result["success"]:
            logging.info(f"WVP数据同步完成: {sync_result['message']}")
        else:
            logging.warning(f"WVP数据同步失败: {sync_result['message']}")
    except Exception as e:
        logging.warning(f"WVP数据同步异常: {e}")
    
    # 初始化AI服务（如果需要）
    try:
        # 这里将在后续任务中实现AI服务初始化
        logging.info("AI服务初始化完成")
    except Exception as e:
        logging.warning(f"AI服务初始化失败: {e}")
    
    logging.info("系统启动完成")
    yield
    
    # 关闭时执行
    logging.info("简化校园数字孪生系统关闭中...")
    logging.info("系统关闭完成")


# 设置日志
setup_logging()

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    description="简化的校园数字孪生系统API",
    version=settings.VERSION,
    docs_url="/docs",
    redoc_url="/redoc",
    lifespan=lifespan
)

# 配置CORS - 开发环境宽松配置
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # 开发环境允许所有来源
    allow_credentials=True,
    allow_methods=["GET", "POST", "PUT", "DELETE", "OPTIONS", "HEAD", "PATCH"],
    allow_headers=["*"],
    expose_headers=["*"],
)

# 添加基本中间件
from api.middleware import error_handling_middleware, logging_middleware
app.middleware("http")(error_handling_middleware)
app.middleware("http")(logging_middleware)


# 健康检查端点
@app.get("/health")
async def health_check():
    """系统健康检查"""
    return {
        "status": "healthy",
        "app_name": settings.APP_NAME,
        "version": settings.VERSION,
        "message": "简化校园数字孪生系统运行正常"
    }


# 根路径
@app.get("/")
async def root():
    """根路径信息"""
    return {
        "message": settings.APP_NAME,
        "version": settings.VERSION,
        "docs": "/docs",
        "health": "/health"
    }


# 包含API路由
from api.main import api_router
from api.endpoints import wvp_unified

app.include_router(api_router, prefix=settings.API_PREFIX)
app.include_router(wvp_unified.router, prefix="/api/wvp", tags=["WVP Unified"])

# 所有API路由已通过 api_router 包含，无需额外路由


if __name__ == "__main__":
    import uvicorn
    uvicorn.run(
        "main:app",
        host=settings.HOST,
        port=settings.PORT,
        reload=settings.is_debug(),
        log_config=None  # 使用自定义日志配置
    )